/*
 * Copyright (c) 2020 rxi
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to
 * deal in the Software without restriction, including without limitation the
 * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
 * sell copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
 * IN THE SOFTWARE.
 */

#include <stdint.h>
#include <stdio.h>
#include <time.h>
#include <stdarg.h>

#include "FreeRTOS.h"

#include "log.h"

static enum LOG_LEVEL _level = LOG_DEBUG;
extern __IO uint32_t uwTick;
static const char *level_strings[] = {
    "D", "I", "W", "E", "F"};

#ifdef LOG_USE_COLOR
static const char *level_colors[] = {
    "\x1b[36m", "\x1b[32m", "\x1b[33m", "\x1b[31m", "\x1b[31m"};
#endif

const char *log_level_string(enum LOG_LEVEL level)
{
    return level_strings[level];
}

void log_set_level(enum LOG_LEVEL level)
{
    _level = level;
}

void log_log(enum LOG_LEVEL level, const char *tag, const char *fmt, ...)
{
    va_list ap;
    struct tm *tm;
    uint32_t sec, ms;
    char buf[16];
    char buffer[256];
    if (level < _level)
        return;
    sec = uwTick / 1000;
    ms = uwTick % 1000;
    tm = localtime(&sec);
    buf[strftime(buf, sizeof(buf), "%H:%M:%S", tm)] = '\0';
#ifdef LOG_USE_COLOR
    // fprintf(
    //   file, "%s %s%-5s\x1b[0m \x1b[90m%s:%d:\x1b[0m ",
    //   buf, level_colors[ev->level], level_strings[ev->level],
    //   ev->file, ev->line);
    fprintf(
        file, "%s %s",
        buf, level_colors[ev->level]);
#else
    printf("%s.%03d %s %s: ", buf, ms, level_strings[level], tag);
#endif
    va_start(ap, fmt);
    vsnprintf(buffer, sizeof(buffer), fmt, ap);
    va_end(ap);
    printf("%s\r\n", buffer);
}
